﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ValidationFramework.Reflection;
using System.Reflection;

namespace ValidationFramework
{
	public class PropertyKey
	{
		public TypeKey TypeKey { get; set; }
        string _propertyName;

		/// <summary>
		/// Initializes a new instance of the PropertyKey class.
		/// </summary>
		public PropertyKey(TypeKey key, string propertyName)
		{
			TypeKey = key;
			_propertyName = propertyName;
		}

        public string PropertyName
        {
            get { return _propertyName; }
        }
        

		public PropertyInfo ResolvePropertyInfo()
		{ 
			return Type.GetTypeFromHandle(TypeKey.TypeHandle).GetProperty(_propertyName);
		}

		/// <summary>
		/// Uses reflection to get the represented property type's runtimeTypeHandle
		/// </summary>
		/// <returns></returns>
		public RuntimeTypeHandle ResolvePropertyTypeHandle()
		{
			var type = Type.GetTypeFromHandle(TypeKey.TypeHandle);
			var property = type.GetProperty(_propertyName);
			return property.PropertyType.TypeHandle;
		}
		
		// --- To support using as a dictionary key
		public override bool Equals(object obj)
		{
			var key = (PropertyKey)obj;
			return this.TypeKey.Equals(key.TypeKey) && this._propertyName == key._propertyName;
		}

		public override int GetHashCode()
		{
			//TODO: this is probably a poor hash algorithm. Its probably ok, but if we can come up with a better one replace this.
			return TypeKey.GetHashCode() + _propertyName.GetHashCode();
		}
	}
}
